import { Component } from '@angular/core';
import { SelectRequireComponent } from '../../purchase-order/select-require/select-require.component';
import { SelectSupplierComponent } from 'src/app/@shared/components/select-supplier/select-supplier.component';
import { SelectUserComponent } from 'src/app/@shared/components/select-user/select-user.component';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { environment } from 'src/environments/environment';
import { SelectMaterialComponent } from 'src/app/@shared/components/select-material/select-material.component';
import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';
import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { SupplierPriceService } from 'src/app/@core/services/supplierPrice/supplier-price.service';
import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { PurchaseService } from 'src/app/@core/services/purchase/purchase.service';
import { UserService } from 'src/app/@core/services/user/user.service';
import { Router } from '@angular/router';
import { DialogService, DValidateRules, FormLayout, TableWidthConfig } from '@devui';

// 采购结算单接口定义
export interface PurchaseSettlement {
  settlementId: number | null;
  settlementNum: string;
  settlementDate: Date;
  purchaseOrderNum: string;
  purchaseOrderId: number | null;
  supplierId: number;
  supplyShortName: string;
  supplyChineseName: string;
  supplyEnglishName: string;
  supplyContactId: number;
  supplyContactName: string;
  purchaseManId: number;
  purchaseManName: string;
  departmentId: number;
  departmentName: string;
  settlementMethodId: number;
  settlementMethodName: string;
  currencyId: number;
  currencyName: string;
  paymentPeriodId: number;
  paymentPeriodName: string;
  settlementAmount: number;
  settlementAmountNoTax: number;
  taxAmount: number;
  /** 实付款（本次付款金额） */
  paidAmount: number;
  /** 未付款（应付-实付，自动计算） */
  unpaidAmount: number;
  settlementStatus: string;
  paymentStatus: string;
  approvalStatus: string;
  isClosed: boolean;
  remark: string;
  files: string[];
  fileRemarks: string[];
  creator: string;
  createDate: Date | null;
  settlementParts: PurchaseSettlementPart[];
  supplyNum: string;
}

export interface PurchaseSettlementPart {
  settlementPartId: number | null;
  materialCode: string;
  materialName: string;
  materialSpec: string;
  materialUnit: string;
  materialId: number;
  image: string;
  purchaseQuantity: number;
  receivedQuantity: number;
  settlementQuantity: number;
  unitPrice: number;
  unitPriceWithTax: number;
  taxRate: number;
  settlementAmount: number;
  settlementAmountWithTax: number;
  taxAmount: number;
  remark: string;
  purchaseOrderPartId: number | null;
  isSettled: boolean;
  realTimeInventory: number;
}

@Component({
  selector: 'app-add-purchase-settlement',
  templateUrl: './add-purchase-settlement.component.html',
  styleUrls: ['./add-purchase-settlement.component.scss']
})
export class AddPurchaseSettlementComponent {
   Math = Math;
    msgs: Array<Object> = [];
    UrlHead: any = environment.modifiedApiUrl;
    layoutDirection: FormLayout = FormLayout.Horizontal;
    isSubmit: boolean = false;
    tableWidthConfig: TableWidthConfig[] = [
      {
        field: '操作',
        width: '150px',
      },
      {
        field: '物料编码',
        width: '150px',
      },
      {
        field: '图片',
        width: '150px',
      },
      {
        field: '物料名称',
        width: '150px',
      },
      {
        field: '物料规格',
        width: '150px',
      },
      {
        field: '物料描述',
        width: '150px',
      },
      {
        field: '物料单位',
        width: '150px',
      },
      {
        field: '采购数量',
        width: '150px',
      },
      {
        field: '已入库数量',
        width: '150px',
      },
      {
        field: '结算数量',
        width: '200px',
      },
      {
        field: '单价(不含税)',
        width: '200px',
      },
      {
        field: '单价(含税)',
        width: '200px',
      },
      {
        field: '税率',
        width: '150px',
      },
      {
        field: '结算金额(不含税)',
        width: '200px',
      },
      {
        field: '结算金额(含税)',
        width: '200px',
      },
      {
        field: '税额',
        width: '150px',
      },
      {
        field: '采购订单号',
        width: '150px',
      },
      {
        field: '备注',
        width: '250px',
      }
    ]; //表格宽度配置
    taxRate: number = 13;
    customerContact: any;
    loadData: boolean;
    purchaseSettlement: PurchaseSettlement = {
      settlementId: null, // 结算单ID
  settlementNum: '', // 付款单号
  settlementDate: new Date(), // 付款日期
      purchaseOrderNum: '', // 采购订单号
      purchaseOrderId: null, // 采购订单ID
      supplierId: 0, // 供应商ID
      supplyShortName: '', // 供应商简称
      supplyChineseName: '', // 供应商中文名
      supplyEnglishName: '', // 供应商英文名
      supplyContactId: 0, // 供应商联系人Id
      supplyContactName: '', // 供应商联系人名称
      purchaseManId: 0, // 业务员Id
      purchaseManName: '', // 业务员名称
      departmentId: 0, // 部门Id
      departmentName: '', // 部门名称
      settlementMethodId: 0, // 结算方式ID
      settlementMethodName: '', // 结算方式名称
      currencyId: 0, // 交易币种ID
      currencyName: '', // 交易币种名称
      paymentPeriodId: 0, // 付款账期ID
      paymentPeriodName: '', // 付款账期名称
  settlementAmount: 0, // 应付款(含税)
  settlementAmountNoTax: 0, // 应付款(不含税)
      taxAmount: 0, // 税额
  paidAmount: 0, // 实付款
  unpaidAmount: 0, // 未付款（自动计算）
      settlementStatus: '待结算', // 结算状态
  paymentStatus: '未付款', // 付款状态
      approvalStatus: '未开始审核', // 审核状态
      isClosed: false, // 是否结案
      remark: '', // 备注
      files: [], // 附件
      fileRemarks: [], // 附件备注
      creator: '', // 制单人
      createDate: null, // 制单日期
      settlementParts: [
        {
          settlementPartId: null, // 结算物料行ID
          materialCode: '', // 物料编码
          materialName: '', // 物料名称
          materialSpec: '', // 物料规格
          materialUnit: '', // 物料单位
          materialId: 0, // 物料ID
          image: '', // 图片
          purchaseQuantity: 0, // 采购数量
          receivedQuantity: 0, // 已入库数量
          settlementQuantity: 0, // 结算数量
          unitPrice: 0, // 单价(不含税)
          unitPriceWithTax: 0, // 单价(含税)
          taxRate: 0, // 税率
          settlementAmount: 0, // 结算金额(不含税)
          settlementAmountWithTax: 0, // 结算金额(含税)
          taxAmount: 0, // 税额
          remark: '', // 备注
          purchaseOrderPartId: null, // 采购订单物料行ID
          isSettled: false, // 是否已结算
          realTimeInventory: 0 // 实时库存
        },
      ],
      supplyNum: ''
    };
    purchaseSettlementRules: { [key: string]: DValidateRules } = {
      settlementNum: {
        messageShowType: 'text',
        validators: [
          { required: true, message: '*付款单号不能为空' },
          { minlength: 2, message: '*付款单号长度至少为2' },
          { maxlength: 40, message: '*付款单号长度至多为40' },
          { pattern: /^[^\s]*$/, message: '*付款单号不能包含空格' },
        ],
      },
      purchaseManName: {
        messageShowType: 'text',
        validators: [{ required: true, message: '*业务员不能为空' }],
      },
      supply: {
        messageShowType: 'text',
        validators: [{ required: true, message: '*供应商不能为空' }],
      },
      purchaseOrderNum: {
        messageShowType: 'text',
        validators: [{ required: true, message: '*采购订单不能为空' }],
      },
      materialCode: {
        messageShowType: 'text',
        validators: [{ required: true, message: '*物料不能为空' }],
      },
      settlementDate: {
        messageShowType: 'text',
  validators: [{ required: true, message: '*付款日期不能为空' }],
      },
      settlementQuantity: {
        messageShowType: 'text',
        validators: [{ required: true, message: '*结算数量不能为空' }],
      },
    };
    options = [
      { label: '检验', value: true },
      { label: '不检验', value: false }
    ]
    supplyContactOption = []; // 供应商联系人
    supplyContact = {}; //供应商联系人
    settlementMethodOption = []; // 结算方式
    settlementMethod = {}; //结算方式
    currencyOption = []; // 交易币种
    currency = {}; //交易币种
    collectionPeriodOption = []; // 付款账期
    collectionPeriod = {}; //付款账期
    fujianNumber: any = 0;
    defaultTaxRate = 0;
    constructor(
      private DialogService: DialogService,
      private Router: Router,
      private UserService: UserService,
      private PurchaseService: PurchaseService,
      private CustomerService: CustomerService,
      private SupplierPriceService: SupplierPriceService,
      private EncodeRulesService: EncodeRulesService,
      private StorehouseService: StorehouseService,
      private ReviewFlowService: ReviewRolesService
    ) {}
    ngOnInit(): void {
      // 生成采购付款单编号
      this.EncodeRulesService.GenerateWarehouseCodeRule(
        '采购付款单',
        '采购付款单'
      ).subscribe((data: any) => {
        this.purchaseSettlement.settlementNum = data;
      });
      const userinfoString = localStorage.getItem('userinfo');
      if (userinfoString) {
        this.purchaseSettlement.creator = JSON.parse(userinfoString).username;
      }
      this.CustomerService.GetPagedCurrency(1, 9999).subscribe((res: any) => {
        this.currencyOption = res.items;
      });
      this.CustomerService.GetPagedCollectionPeriod({
        PageSize: 999,
        PageNumber: 1,
        SearchStatus: '付款',
      }).subscribe((res: any) => {
        this.collectionPeriodOption = res.items;
      });
      this.CustomerService.GetPagedSettlementMethod(1, 9999).subscribe(
        (res: any) => {
          this.settlementMethodOption = res.items;
        }
      );
    }
    selectMaterial(rowItem: any, dialogtype?: string) {
      const results = this.DialogService.open({
        id: 'Add',
        maxHeight: '400px',
        width: '800px',
        backdropCloseable: true,
        data: '',
        title: '选择物料',
        content: SelectMaterialComponent,
        dialogtype: dialogtype,
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              rowItem.materialId = results.modalContentInstance.selectData.partId;
              rowItem.materialCode = results.modalContentInstance.selectData.partNum;
              rowItem.materialName = results.modalContentInstance.selectData.partName;
              rowItem.materialUnit = results.modalContentInstance.selectData.partUOM;
              rowItem.materialSpec = results.modalContentInstance.selectData.partType;
              rowItem.image = results.modalContentInstance.selectData.fileURL;
              rowItem.taxRate = this.defaultTaxRate / 100;

              this.SupplierPriceService.getVaildPriceByPartId(
                rowItem.materialId
              ).subscribe(
                (res: any) => {
                  rowItem.unitPriceWithTax = res[0].price;
                  this.calculateAmount(rowItem);
                },
                (error: any) => {
                  rowItem.unitPriceWithTax = 0;
                  this.calculateAmount(rowItem);
                }
              );
              this.StorehouseService.GetPartsAllInventory([
                rowItem.materialId,
              ]).subscribe((res: any) => {
                rowItem.realTimeInventory = res[0].inventory;
              });

              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
    showToast(type: any, summary: any, content: any) {
      switch (type) {
        default:
          this.msgs = [{ severity: type, summary: summary, content: content }];
      }
    } //提示框
    addRow() {
      this.purchaseSettlement.settlementParts.push({
        settlementPartId: null,
        materialCode: '',
        materialName: '',
        materialSpec: '',
        materialUnit: '',
        materialId: 0,
        image: '',
        purchaseQuantity: 0,
        receivedQuantity: 0,
        settlementQuantity: 0,
        unitPrice: 0,
        unitPriceWithTax: 0,
        taxRate: this.defaultTaxRate / 100,
        settlementAmount: 0,
        settlementAmountWithTax: 0,
        taxAmount: 0,
        remark: '',
        purchaseOrderPartId: null,
        isSettled: false,
        realTimeInventory: 0
      });
    } //添加行
    deleteRow(index: number) {
      this.purchaseSettlement.settlementParts.splice(index, 1);
      if (this.purchaseSettlement.settlementParts.length == 0) {
        this.addRow();
      }
      this.purchaseSettlement.settlementParts.map((item: any) => {
        this.calculateAmount(item);
      });
    }
    isStartApproval: boolean = false;
    isStartApprovalChange() {
      this.isStartApproval = true;
    }
    submit($event: any) {
      if ($event.valid) {
        if (!this.validateSettlement(this.purchaseSettlement)) {
          return;
        }
        this.purchaseSettlement.createDate = new Date();
        this.purchaseSettlement.settlementParts.forEach((item) => {
          // 设置结算单号到明细行
        });
        console.log(this.purchaseSettlement);

  // 采购付款单提交（TODO: 在 PurchaseService 中新增 addPurchasePayment 方法）
  console.log('提交采购付款单数据:', this.purchaseSettlement);

        // 模拟API调用成功
        setTimeout(() => {
          this.isSubmit = false;
          if (this.isStartApproval) {
            this.ReviewFlowService.StartApprovalFlow('采购付款单审核流配置', [
              this.purchaseSettlement.settlementNum,
            ]).subscribe(
              (data: any) => {
                this.showToast('success', '成功', '流程发起成功');
                setTimeout(() => {
                  this.cancel();
                }, 1000);
              },
              (error: any) => {
                this.showToast('error', '失败', error.error);
                setTimeout(() => {
                  this.cancel();
                }, 1000);
              }
            );
          } else {
            this.showToast('success', '成功', '提交成功');
            setTimeout(() => {
              this.cancel();
            }, 1000);
          }
        }, 1000);
      } else {
        this.showToast('warn', '错误', '请检查表单是否填写正确');
      }
    }
    getImagesArray(fileURL: string): string[] {
      let urls = fileURL.split(',');
      urls = urls.map((url) => environment.modifiedApiUrl + url);
      return urls;
    }
    cancel() {
      this.Router.navigateByUrl('/pages/purchase/purchase-settlement');
    }
    fujian(dialogtype?: string) {
      const results = this.DialogService.open({
  title: '采购付款单附件',
        width: '800px',
        backdropCloseable: false,
        data: {
          data: '付款附件',
          urls: this.purchaseSettlement.files,
        },
        content: AttachmentComponent,
        dialogtype: dialogtype,
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              this.purchaseSettlement.files.push(results.modalContentInstance.urls);
              this.fujianNumber = this.purchaseSettlement.files.length;
              results.modalInstance.hide();
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
    validateSettlement(purchaseSettlement: PurchaseSettlement): boolean {
      for (const [index, item] of purchaseSettlement.settlementParts.entries()) {
        if (!item.materialCode) {
          this.showToast('warn', '错误', `第${index + 1}行物料编码不能为空`);
          return false;
        }
        if (item.settlementQuantity <= 0) {
          this.showToast('warn', '错误', `第${index + 1}行结算数量必须大于0`);
          return false;
        }
        if (item.unitPriceWithTax <= 0) {
          this.showToast('warn', '错误', `第${index + 1}行单价(含税)必须大于0`);
          return false;
        }
      }
      return true;
    }
    selectUser() {
      const results = this.DialogService.open({
        id: 'Add',
        maxHeight: '400px',
        width: '800px',
        backdropCloseable: true,
        data: '',
        title: '选择业务员',
        content: SelectUserComponent,
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              this.purchaseSettlement.purchaseManName =
                results.modalContentInstance.selectData.name;
              this.purchaseSettlement.purchaseManId =
                results.modalContentInstance.selectData.id;
              this.UserService.GetDepartmentById(
                results.modalContentInstance.selectData.departmentId
              ).subscribe((res: any) => {
                this.purchaseSettlement.departmentName = res.name;
                this.purchaseSettlement.departmentId = res.departmentId;
              });
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
    selectDepartment() {
      if (!this.purchaseSettlement.purchaseManId) {
        this.showToast('warn', '请选择申请人', '请选择申请人');
      }
    }
    selectPurchaseOrder() {
      // TODO: 实现选择采购订单的功能
      console.log('选择采购订单功能待实现');
    }
    selectSupply(reset?: boolean) {
      const results = this.DialogService.open({
        id: 'Add',
        maxHeight: '400px',
        width: '800px',
        backdropCloseable: true,
        data: '',
        title: '选择供应商',
        content: SelectSupplierComponent,
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              this.purchaseSettlement.supplyShortName =
                results.modalContentInstance.selectData.supplyShortName;
              this.purchaseSettlement.supplierId =
                results.modalContentInstance.selectData.supplyId;
              this.purchaseSettlement.supplyChineseName =
                results.modalContentInstance.selectData.supplyChineseName;
              this.purchaseSettlement.supplyEnglishName =
                results.modalContentInstance.selectData.supplyEnglishName;
              this.supplyContactOption =
                results.modalContentInstance.selectData.supplyContacts;
              this.defaultTaxRate =
                results.modalContentInstance.selectData.taxRate;
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }

    selectSupplyContact($event: any) {
      this.purchaseSettlement.supplyContactId = $event.supplyContactId;
      this.purchaseSettlement.supplyContactName = $event.supplyContactName;
    }
    selectcurrency($event: any) {
      this.purchaseSettlement.currencyId = $event.currencyId;
      this.purchaseSettlement.currencyName = $event.currencyName;
    }
    selectsettlementMethodOption($event: any) {
      this.purchaseSettlement.settlementMethodId = $event.settlementMethodId;
      this.purchaseSettlement.settlementMethodName = $event.settlementMethodName;
    }
    selectcollectionPeriodOption($event: any) {
      this.purchaseSettlement.paymentPeriodId = $event.collectionPeriodId;
      this.purchaseSettlement.paymentPeriodName = $event.collectionPeriodName;
    }
    taxRateChange(rowitem: any, value: number) {
      rowitem.taxRate = value / 100;
      this.calculateAmount(rowitem);
    } //税率改变
    settlementQuantityChange(rowitem: any, value: number) {
      rowitem.settlementQuantity = value;
      this.calculateAmount(rowitem);
    } //结算数量改变
    unitPriceWithTaxChange(rowitem: any, value: number) {
      rowitem.unitPriceWithTax = value;
      this.calculateAmount(rowitem);
    }
    calculateAmount(item: any): void {
      //计算不含税单价，并保留4位小数
      item.unitPrice = +(item.unitPriceWithTax / (1 + item.taxRate)).toFixed(4);
      item.settlementAmountWithTax = +(item.unitPriceWithTax * item.settlementQuantity).toFixed(4);
      item.taxAmount = +((item.unitPriceWithTax - item.unitPrice) * item.settlementQuantity).toFixed(4);
      item.settlementAmount = +(item.settlementAmountWithTax - item.taxAmount).toFixed(4);
      this.calculateTotalAmount();
    }
    calculateTotalAmount(): void {
      // 重置总计属性
      this.purchaseSettlement.settlementAmount = 0;
      this.purchaseSettlement.settlementAmountNoTax = 0;
      this.purchaseSettlement.taxAmount = 0;

      // 遍历并累加各项值
      this.purchaseSettlement.settlementParts.forEach((item) => {
        this.purchaseSettlement.settlementAmount += item.settlementAmountWithTax;
        this.purchaseSettlement.settlementAmountNoTax += item.settlementAmount;
        this.purchaseSettlement.taxAmount += item.taxAmount;
      });

      // 保留4位小数
      this.purchaseSettlement.settlementAmount = parseFloat(
        this.purchaseSettlement.settlementAmount.toFixed(4)
      );
      this.purchaseSettlement.settlementAmountNoTax = parseFloat(
        this.purchaseSettlement.settlementAmountNoTax.toFixed(4)
      );
      this.purchaseSettlement.taxAmount = parseFloat(
        this.purchaseSettlement.taxAmount.toFixed(4)
      );

      // 自动计算未付款：应付款(含税合计) - 实付款
      this.calculateUnpaidAmount();
    }

    // 实付款修改
    paidAmountChange(value: number) {
      this.purchaseSettlement.paidAmount = Number(value) || 0;
      this.calculateUnpaidAmount();
    }

    // 计算未付款
    private calculateUnpaidAmount() {
      const payable = this.purchaseSettlement.settlementAmount || 0;
      const paid = this.purchaseSettlement.paidAmount || 0;
      let unpaid = +(payable - paid).toFixed(4);
      // 若超付，提示并将未付款置为0
      if (unpaid < 0) {
        this.showToast('warn', '提示', '实付款大于应付款');
        unpaid = 0;
      }
      this.purchaseSettlement.unpaidAmount = unpaid;
    }
}
